from fastapi import Depends
from fastapi_amis_admin.globals.deps import SyncSess
from sqlalchemy import text
from superstream import Stream

from backend.apps.common import PageResult
from backend.apps.user.models import UserQueryParams, SysUser


class UserService:


    def page(params: UserQueryParams, sess: SyncSess) -> PageResult:
        offset = (params.page - 1) * params.size
        sql_where = []
        if params and params.username:
            sql_where.append(SysUser.username.contains(params.username))
        query = sess.query(SysUser).where(*sql_where)
        results = query.offset(offset).limit(params.size).all()
        total = query.count()
        return PageResult(page=params.page, size=params.size, total=total, list=results)


    def detail(id: int, sess: SyncSess) -> SysUser:
        obj = sess.get(SysUser, id)
        return obj

    def save( sess: SyncSess, data: SysUser):
        sess.add(data)

    def update(data: SysUser, sess: SyncSess):
        print(dict(data))
        sess.query(SysUser).filter(SysUser.id == data.id).update(dict(data))

    def delete(id: int, sess: SyncSess):
        sess.query(SysUser).filter(SysUser.id == id).delete()
